package com.mas.framework.security.config;

import com.mas.framework.security.core.filter.TokenAuthenticationFilter;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author godyao
 * @description 自定义的 Spring Security 配置适配器实现
 * @date 2023年01月28日13:54
 */
@AutoConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class MasWebSecurityConfigurerAdapter {
    @Resource
    private SecurityProperties securityProperties;

    /**
     * 认证失败处理类 Bean
     */
    @Resource
    private AuthenticationEntryPoint authenticationEntryPoint;
    /**
     * 权限不够处理器 Bean
     */
    @Resource
    private AccessDeniedHandler accessDeniedHandler;

    /**
     * Token 认证过滤器 Bean
     */
    @Resource
    private TokenAuthenticationFilter authenticationTokenFilter;

    @Resource
    private ApplicationContext applicationContext;


    /**
     * 由于 Spring Security 创建 AuthenticationManager 对象时，没声明 @Bean 注解，导致无法被注入
     * 通过覆写父类的该方法，添加 @Bean 注解，解决该问题
     */
    @Bean
    public AuthenticationManager authenticationManagerBean(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    protected SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        // 获得 @PermitAll 带来的 URL 列表，免登录
        MultiValueMap<HttpMethod, String> permitAllUrls = getPermitAllUrlsFromAnnotations();
        // 登出
        httpSecurity
        // 开启跨域
                .cors().and()
                // CSRF 禁用，因为不使用 Session
                .csrf().disable()
                // 基于 token 机制，所以不需要 Session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .headers().frameOptions().disable().and()
                // 一堆自定义的 Spring Security 处理器
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/*.html", "/**/*.html", "/**/*.css", "/**/*.js").permitAll()
                // 1.2 设置 @PermitAll 无需认证
                .antMatchers(HttpMethod.GET, permitAllUrls.getOrDefault(HttpMethod.GET, Collections.emptyList()).toArray(new String[0])).permitAll()
                .antMatchers(HttpMethod.POST, permitAllUrls.getOrDefault(HttpMethod.POST, Collections.emptyList()).toArray(new String[0])).permitAll()
                .antMatchers(HttpMethod.PUT, permitAllUrls.getOrDefault(HttpMethod.PUT, Collections.emptyList()).toArray(new String[0])).permitAll()
                .antMatchers(HttpMethod.DELETE, permitAllUrls.getOrDefault(HttpMethod.DELETE, Collections.emptyList()).toArray(new String[0])).permitAll()
                .antMatchers(HttpMethod.PATCH, permitAllUrls.getOrDefault(HttpMethod.PATCH, Collections.emptyList()).toArray(new String[0])).permitAll()
                // 1.3 基于 mas.security.permit-all-urls 无需认证
                .antMatchers(securityProperties.getPermitAllUrls().toArray(new String[0])).permitAll()
                .antMatchers("/swagger-ui.html").anonymous()
                .antMatchers("/swagger-resources/**").anonymous()
                .antMatchers("/webjars/**").anonymous()
                .antMatchers("/*/api-docs").anonymous()
                .anyRequest().authenticated();
                //.anyRequest().anonymous();
        // 添加 Token Filter
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        return httpSecurity.build();
    }

    /**
     * 获取所有被 @PermitAll 修饰的接口
     * @author godyao
     * @return org.springframework.util.MultiValueMap<org.springframework.http.HttpMethod,java.lang.String>
     * @date 2023/2/1 14:29
     */
    private MultiValueMap<HttpMethod, String> getPermitAllUrlsFromAnnotations() {
        final MultiValueMap<HttpMethod, String> result = new LinkedMultiValueMap<>();
        // 获得接口对应的 HandlerMethod 集合
        final RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) applicationContext.getBean("requestMappingHandlerMapping");
        // 获取所有 controller 方法
        final Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            final HandlerMethod method = entry.getValue();
            if (!method.hasMethodAnnotation(PermitAll.class)) {
                // 没有被 @PermitAll 修饰
                continue;
            }
            final RequestMappingInfo key = entry.getKey();
            if (key.getPatternsCondition() == null) {
                // url匹配路径不存在
                continue;
            }
            final Set<String> urls = key.getPatternsCondition().getPatterns();
            final List<String> urlList = new ArrayList<>(urls);
            // 根据请求方法，添加到 result 结果
            key.getMethodsCondition().getMethods().forEach(requestMethod -> {
                switch (requestMethod) {
                    case GET:
                        result.addAll(HttpMethod.GET, urlList);
                        break;
                    case POST:
                        result.addAll(HttpMethod.POST, urlList);
                        break;
                    case PUT:
                        result.addAll(HttpMethod.PUT, urlList);
                        break;
                    case DELETE:
                        result.addAll(HttpMethod.DELETE, urlList);
                        break;
                    case PATCH:
                        result.addAll(HttpMethod.PATCH, urlList);
                        break;
                    default:
                        break;
                }
            });
        }
        return result;
    }

}
